package com.navi.mould1.service.impl;

import com.navi.bean.in.ConditionBean;
import com.navi.bean.out.retAutoIns_report.RetAutoInsReportGridOut;
import com.navi.bean.sql.SqlVo;
import com.navi.core.context.HistoryContext;
import com.navi.core.util.JacksonUtil;
import com.navi.core.util.LoggerUtil;
import com.navi.mould1.pojo.ToolToolgLineFabPojo;
import com.navi.mould1.reportUtils.LKingSortUtil;
import com.navi.mould1.service.IRetAutoInsReportService;
import com.navi.mould1.tx.xpretautoins.XpretautoinsI;
import com.navi.mould1.tx.xpretautoins.XpretautoinsO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.navi.bean.sql.SqlVo.jointInSql;
import static com.navi.core.util.JdbcUtils.mySql_QueryRunner_QueryListBySql;
import static com.navi.core.util.JdbcUtils.mySql_QueryRunner_Update;


@Slf4j
@Service
@Transactional
public class RetAutoInsReportServiceImpl implements IRetAutoInsReportService {

    @Override
    public String subMainProc(String strInObj) {
        HistoryContext.clear(this.getClass());

        XpretautoinsI inTrx = new XpretautoinsI();
        XpretautoinsO outTrx = new XpretautoinsO();

        inTrx = JacksonUtil.fromJson(strInObj, XpretautoinsI.class);
        log.info(strInObj);

        String actionFlg = inTrx.getAction_flg();
        switch (actionFlg) {
            case "U":
                outTrx = update_Proc(inTrx);
                break;
            default:
                break;
        }

        final String strOutTrx = JacksonUtil.toJSONStr(outTrx);
        return strOutTrx;
    }




    public List<RetAutoInsReportGridOut> getGridData(ConditionBean conditions) {
        //SQL优化：子查询独立出来
        final SqlVo queryTool_sql = new SqlVo();
        queryTool_sql.appendSql("SELECT");
        queryTool_sql.appendSql("A.tool_id AS tool_id_fk,");
        queryTool_sql.appendSql("A.tool_dsc as tool_id,");
        queryTool_sql.appendSql("B.toolg_id as toolg_id_fk,");
        queryTool_sql.appendSql("b_3.data_desc as toolg_id,");
        queryTool_sql.appendSql("A.bay_id as line_id_fk,");
        queryTool_sql.appendSql("b_2.data_desc as line_id,");
        queryTool_sql.appendSql("A.fab_id_fk as fab_id_fk,");
        queryTool_sql.appendSql("b_1.data_desc as fab_id");
        queryTool_sql.appendSql("FROM");
        queryTool_sql.appendSql("bis_tool A");
        queryTool_sql.appendSql("LEFT JOIN icim_jn.bis_tool_gr B ON A.ROOT_TOOL_ID = B.TOOL_ID_FK");
        queryTool_sql.appendSql("LEFT JOIN (select data_ext,data_desc from icim_jn.bis_data where data_cate = 'FBID') b_1 ON A.FAB_ID_FK = b_1.data_ext");
        queryTool_sql.appendSql("LEFT JOIN (select data_ext,data_desc from icim_jn.bis_data where data_cate = 'AREA') b_2 ON A.BAY_ID = b_2.data_ext");
        queryTool_sql.appendSql("LEFT JOIN (select data_ext,data_desc from icim_jn.bis_data where data_cate = 'TOLG') b_3 ON B.TOOLG_ID = b_3.data_ext");
        queryTool_sql.appendSql("WHERE 1=1");
        //if (StringUtils.isNotEmpty(conditions.getFab_id())) queryTool_sql.appendSql("AND b_1.data_ext in" + jointInSql(conditions.getFab_id()));
        //if (StringUtils.isNotEmpty(conditions.getBay_id())) queryTool_sql.appendSql("AND b_2.data_ext in" + jointInSql(conditions.getBay_id()));
        //if (StringUtils.isNotEmpty(conditions.getToolg_id())) queryTool_sql.appendSql("AND b_3.data_ext in " + jointInSql(conditions.getToolg_id()));
        //if (StringUtils.isNotEmpty(conditions.getTool_id())) queryTool_sql.appendSql("AND A.TOOL_ID_FK in" + jointInSql(conditions.getTool_id()));
        List<ToolToolgLineFabPojo> tool_toolg_line_fab_list = mySql_QueryRunner_QueryListBySql(queryTool_sql, ToolToolgLineFabPojo.class);

        final SqlVo sqlVo = new SqlVo();
        sqlVo.appendSql("SELECT");
        sqlVo.appendSql("A.TOOL_ID_FK,");
        //sqlVo.appendSql("b_3.tool_dsc AS TOOL_ID,");
        sqlVo.appendSql("A.DATA_GROUP,");
        sqlVo.appendSql("A.EVT_TIMESTAMP,");
        sqlVo.appendSql("A.EVT_USR,");
        sqlVo.appendSql("A.FAB_ID_FK,");
        //sqlVo.appendSql("b_1.data_desc AS FAB_ID,");
        sqlVo.appendSql("A.LINE_ID_FK,");
        //sqlVo.appendSql("b_2.data_desc AS LINE_ID,");
        sqlVo.appendSql("A.DATA_VALUE,");
        sqlVo.appendSql("A.BEGIN_TIMESTAMP,");
        sqlVo.appendSql("A.determine_flg,");
        sqlVo.appendSql("A.determine_usr,");
        sqlVo.appendSql("A.determine_timestamp");
        sqlVo.appendSql("FROM ret_auto_ins A");
        //sqlVo.appendSql("LEFT JOIN (select data_ext,data_desc from icim_jn.bis_data where data_cate = 'FBID') b_1 ON A.FAB_ID_FK = b_1.data_ext");
        //sqlVo.appendSql("LEFT JOIN (select data_ext,data_desc from icim_jn.bis_data where data_cate = 'AREA') b_2 ON A.line_id_fk = b_2.data_ext");
        //sqlVo.appendSql("LEFT JOIN (select tool_id,tool_dsc from icim_jn.bis_tool ) b_3 ON A.TOOL_ID_FK = b_3.tool_id");
        if (StringUtils.isNotEmpty(conditions.getTool_type())) sqlVo.appendSql("INNER JOIN ( select tool_id from bis_tool where unit_typ='" + conditions.getTool_type() + "' ) E ON E.tool_id = A.tool_id_fk");
        sqlVo.appendSql("WHERE 1=1");
        //sqlVo.appendSql("AND A.data_group in(SELECT data_group FROM icim_jn.bis_m_item where automatic_check_flg = 'Y')");
        if (StringUtils.isNotEmpty(conditions.getFab_id())) sqlVo.appendSql("AND A.FAB_ID_FK in" + jointInSql(conditions.getFab_id()));
        if (StringUtils.isNotEmpty(conditions.getBay_id())) sqlVo.appendSql("AND A.LINE_ID_FK in" + jointInSql(conditions.getBay_id()));
        if (StringUtils.isNotEmpty(conditions.getTool_id())) sqlVo.appendSql("AND A.TOOL_ID_FK in" + jointInSql(conditions.getTool_id()));
        if (StringUtils.isNotEmpty(conditions.getToolg_id())) sqlVo.appendSql("AND A.TOOL_ID_FK in (select tool_id from icim_jn.bis_tool where root_tool_id in (select tool_id_fk from bis_tool_gr where toolg_id in " + jointInSql(conditions.getToolg_id()) + "))");
        if (StringUtils.isNotEmpty(conditions.getStart_time())) sqlVo.appendSqlAndAddParam("AND A.BEGIN_TIMESTAMP >= ? ", conditions.getStart_time());
        if (StringUtils.isNotEmpty(conditions.getEnd_time())) sqlVo.appendSqlAndAddParam("AND A.BEGIN_TIMESTAMP <= ? ", conditions.getEnd_time());
        sqlVo.appendSql("ORDER BY BEGIN_TIMESTAMP, DATA_GROUP");
        List<RetAutoInsReportGridOut> gridOutList = mySql_QueryRunner_QueryListBySql(sqlVo, RetAutoInsReportGridOut.class);

        //赋值
        gridOutList.forEach(data -> {
            List<ToolToolgLineFabPojo> toolToolgLineFab_list = tool_toolg_line_fab_list.stream().filter(toolToolgLineFab -> data.getTool_id_fk().equals(toolToolgLineFab.getTool_id_fk())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(toolToolgLineFab_list) && toolToolgLineFab_list != null) {
                data.setFab_id(toolToolgLineFab_list.get(0).getFab_id());
                data.setLine_id(toolToolgLineFab_list.get(0).getLine_id());
                data.setTool_id(toolToolgLineFab_list.get(0).getTool_id());
            }
        });
        //排序
        //LKingSortUtil.sort(gridOutList, new String[] { "begin_timestamp", "fab_id", "tool_id", "data_group" }, new boolean[] { false, true });
        return gridOutList;
    }





    @Transactional
    public XpretautoinsO update_Proc(XpretautoinsI inTrx) {
        XpretautoinsO outTrx = new XpretautoinsO();
        if (CollectionUtils.isNotEmpty(inTrx.getIary())){
            SqlVo sqlVo = new SqlVo("update ret_auto_ins set determine_flg = '" + inTrx.getDetermine_flg() +
                    "', determine_timestamp='" + new Timestamp(System.currentTimeMillis()).toString() + "', determine_usr='" + inTrx.getDetermine_usr() + "' where");
            sqlVo.appendSql(inTrx.getIary().stream().map(inIary -> {
                return new StringBuffer("(begin_timestamp = '").append(inIary.getBegin_timestamp()).append("'")
                        .append(" and fab_id_fk = '").append(inIary.getFab_id_fk()).append("'")
                        .append(" and line_id_fk = '").append(inIary.getLine_id_fk()).append("'")
                        .append(" and tool_id_fk = '").append(inIary.getTool_id_fk()).append("')").toString();
            }).collect(Collectors.joining(" or ")));
            try {
                int update_cnt = mySql_QueryRunner_Update(sqlVo);
                outTrx.setRtn_code("0000000");
                outTrx.setRtn_mesg("success");
                outTrx.setUpdate_cnt(String.valueOf(update_cnt));
            } catch (Exception e) {
                log.error(LoggerUtil.stackTraceToString(e));
                e.printStackTrace();
                outTrx.setRtn_code("0000003");
                outTrx.setRtn_mesg(e.getMessage());
            }
        }
        return outTrx;
    }

}
